layui.use(['form', 'jquery', 'upload'], function () {
    let form = layui.form;
    let $ = layui.jquery;
    let upload = layui.upload;

    let prefix = "message"
    let email = localStorage.getItem('email');
    let nickname = localStorage.getItem('nickname');
    $("[name=email]").val(email);
    $("[name=nickname]").val(nickname);
    form.on('submit(message-save)', function (data) {
        for (var key in data.field) {
            var type = $(data.form).find("input[name='" + key + "']").attr("type");
            if (type == "checkbox") {
                var value = "";
                $(data.form).find("input[name='" + key + "']:checked").each(function () {
                    value += $(this).val() + ",";
                })
                if (value != "") {
                    value = value.substr(0, value.length - 1);
                    data.field[key] = value;
                }

            }
        }
        $.ajax({
            url: prefix + '/save',
            data: JSON.stringify(data.field),
            dataType: 'json',
            contentType: 'application/json',
            type: 'post',
            success: function (result) {
                if (result.code == 200) {
                    layer.msg("提交成功", {icon: 1, time: 1000}, function () {
                        localStorage.setItem("email", $("[name=email]").val())
                        localStorage.setItem("nickname", $("[name=nickname]").val())
                        $('#cz').click();
                    });
                } else {
                    layer.msg(result.msg, {icon: 2, time: 1000});
                }
            }
        })
        return false;
    });

    //普通图片上传
    var uploadInst = upload.render({
        elem: '#test1'
        ,url: prefix + '/uploadImg'
        ,field:"layuiFile"
        ,before: function(obj){
            //预读本地文件示例，不支持ie8
            obj.preview(function(index, file, result){
                $('#demo1').attr('src', result); //图片链接（base64）
            });
        }
        ,done: function(res){
            //如果上传失败
            if(res.code != 1){
                return layer.msg('上传失败');
            }
            //上传成功
            $("[name=image]").val(res.data.url);
        }
        ,error: function(){
            //演示失败状态，并实现重传
            var demoText = $('#demoText');
            demoText.html('<span style="color: #FF5722;">上传失败</span> <a class="layui-btn layui-btn-xs demo-reload">重试</a>');
            demoText.find('.demo-reload').on('click', function(){
                uploadInst.upload();
            });
        }
    });
});